import React, { Component } from 'react';
import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import axios from "../../../../http";
import Card from "@iso/containers/UIElements/Card/Card.styles";
import {Fieldset, Form, Label} from "@iso/containers/FirestoreCRUD/Article/Article.styles";
import Input, { Textarea } from '@iso/components/uielements/input';
import Qs from 'qs'
import PageHeader from '@iso/components/utility/pageHeader';
import {Tree} from "antd";
import {DownOutlined} from "@ant-design/icons";
import CkEditor from "@iso/components/Editor/CkEditor";
import Switch from '@iso/components/uielements/switch';
import {convertData} from "./CategoryTreeDataUtils";
import {showErrorMessage, showSuccessMessage} from "@iso/containers/Feedback/Message/MessageUtils";


export default class NoteAdd extends React.Component {


    constructor(props) {
        super(props);
        this.state={data:[],title:'未命名笔记',content:'',categorySelectedKeys:[],autoSave:true,id:''};
    }


    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };

     loadData=() =>{
        axios.post('api/oa/note/category/findMyAll', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let list=data.data

                list=convertData(list,0);

                this.setState({data:list});
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    getCategoryId=()=>{
        let categorySelectedKeys=this.state.categorySelectedKeys;
        if(categorySelectedKeys.length==0){
            return null;
        }
        let categorySelectedKey=categorySelectedKeys[0];
        let categoryId=categorySelectedKey.substring(4,categorySelectedKey.length);
        return categoryId;
    }

    add=() =>{
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content};
        axios.post('api/oa/note/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    showSuccessMessage(data.message)
                }else{
                    showErrorMessage(data.message);
                }
                this.setState({id:data.data})
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    autoAdd=() =>{
        if(this.state.title==''||this.state.content==''){
            return ;
        }
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content};
        axios.post('api/oa/note/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    showSuccessMessage('已自动保存！')
                }else{
                    showErrorMessage(data.message);
                }
                this.setState({id:data.data})
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    autoUpdate=() =>{
         if(this.state.title==''||this.state.content==''){
             return ;
         }
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content,id:this.state.id};
        axios.post('api/oa/note/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    showSuccessMessage('已自动保存！')
                }else{
                    showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    categoryOnSelect = (selectedKeys, info) => {
        this.setState({categorySelectedKeys:selectedKeys})
    }

   componentDidMount() {
        this.loadData()

       this.timer = setInterval(
           () => {
               if(this.state.autoSave==true){
                   if(this.state.id!=""){
                       this.autoUpdate();
                   }else {
                       this.autoAdd();
                   }
               }
           },
           10000
       );
   }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer);
    }

    render() {
    return (
      <LayoutContentWrapper >
          <PageHeader>
              新建笔记
          </PageHeader>
        <LayoutContent>


            <Card
                title=''
                style={{ width: '100%' }}
            >

                <Form >

                    <Fieldset>
                        <Label>自动保存:</Label>
                        <Switch checked={this.state.autoSave}  onChange={()=>{

                            if(this.state.autoSave==true){
                                this.setState({autoSave:false})
                            }else {
                                this.setState({autoSave:true})
                            }
                           }
                        }/>
                    </Fieldset>
                    <Fieldset>
                        <Label>标题:</Label>
                        <Input
                            label="标题"
                            placeholder="标题"
                            value={this.state.title}
                            onChange={e => this.onRecordChange(e, 'title')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>分类:</Label>
                        <Tree
                            switcherIcon={<DownOutlined />}
                            onSelect={this.categoryOnSelect}
                            selectedKeys={this.state.categorySelectedKeys}
                            treeData={this.state.data}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>内容:</Label>
                        <CkEditor handleChange={(data)=>{this.setState({content:data})}} data={this.state.content} />
                    </Fieldset>

                </Form>


            </Card>

        </LayoutContent>
      </LayoutContentWrapper>
    );
  }
}
